import 'package:casdon/modules/lifeCircle/data/model/life_topic_module.dart';
import 'package:casdon/modules/lifeCircle/domain/states/life_topic_list_state.dart';

import 'package:casdon/modules/lifeCircle/providers/life_provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class LifeTopicListNotifier
    extends FamilyAsyncNotifier<LifeTopicListState, String> {
  late final String subjectId;
  int pageSize = 10;
  bool _isRefreshing = false;
  KeepAliveLink? _keepAliveLink;

  @override
  Future<LifeTopicListState> build(String arg) async {
    subjectId = arg;
    ref.onDispose(() {
      _keepAliveLink?.close();
      _keepAliveLink = null;
    });

    final cached = state.valueOrNull;
    if (cached != null && (cached.data?.isNotEmpty ?? false)) {
      Future.microtask(_refreshSilently);
      return cached;
    }

    final fresh = await _fetchData(page: 1);
    _updateKeepAlive(fresh);
    return fresh;
  }

  Future<void> refresh() async {
    await _refreshSilently(force: true);
  }

  Future<LifeTopicListState> _fetchData({
    required int page,
  }) async {
    final ret = await ref
        .read(lifeTopicListUsecaseProvider)
        .execute(id: subjectId, pageNum: page, pageSize: pageSize);
    final rows = ret.rows ?? [];
    final items = LifeTopicModule.listFromApi(rows);
    final consumed = (page - 1) * pageSize + rows.length;
    final hasMore =
        ret.total > 0 ? ret.total > consumed : items.length >= pageSize;

    return LifeTopicListState(
      data: items,
      totalSize: ret.total,
      page: page,
      pageSize: pageSize,
      isLoadingMore: false,
      hasMore: hasMore,
    );
  }

  Future<void> loadMore() async {
    final current = state.valueOrNull;
    if (current == null || current.isLoadingMore || !current.hasMore) return;
    if ((current.data?.length ?? 0) >= current.totalSize) {
      return;
    }
    state = AsyncValue.data(current.copyWith(isLoadingMore: true));

    try {
      final nextPage = current.page + 1;
      final nextState = await _fetchData(page: nextPage);
      final merged = nextState.copyWith(
        data: [
          ...current.data ?? [],
          ...nextState.data ?? [],
        ],
        page: nextPage,
        isLoadingMore: false,
      );
      state = AsyncValue.data(merged);
      _updateKeepAlive(merged);
    } catch (e) {
      state = AsyncValue.data(current.copyWith(isLoadingMore: false));
      debugPrint('Load more error: $e');
    }
  }

  Future<void> _refreshSilently({bool force = false}) async {
    if (_isRefreshing) return;
    _isRefreshing = true;
    final previous = state.valueOrNull;
    try {
      final fresh = await _fetchData(page: 1);
      state = AsyncValue.data(fresh);
      _updateKeepAlive(fresh);
    } catch (e, st) {
      if (previous == null) {
        state = AsyncValue.error(e, st);
      } else if (force) {
        state = AsyncValue.data(previous);
        _updateKeepAlive(previous);
      }
    } finally {
      _isRefreshing = false;
    }
  }

  /// 更新指定 topic 的关注状态
  void updateTopicFollowStatus(String topicId, bool isFollowed) {
    final current = state.valueOrNull;
    if (current == null || current.data == null) return;

    final updatedData = current.data!.map((topic) {
      if (topic.id == topicId) {
        return topic.copyWith(isFollow: isFollowed);
      }
      return topic;
    }).toList();

    final newState = current.copyWith(data: updatedData);
    state = AsyncValue.data(newState);
    _updateKeepAlive(newState);
  }

  /// 更新指定 topic 的点赞状态
  void updateTopicLikeStatus(String topicId, bool isLiked, int newLikesCount) {
    final current = state.valueOrNull;
    if (current == null || current.data == null) return;

    final updatedData = current.data!.map((topic) {
      if (topic.id == topicId) {
        return topic.copyWith(
          isLike: isLiked,
          likes: newLikesCount,
        );
      }
      return topic;
    }).toList();

    final newState = current.copyWith(data: updatedData);
    state = AsyncValue.data(newState);
    _updateKeepAlive(newState);
  }

  void _updateKeepAlive(LifeTopicListState data) {
    if (data.data != null && data.data!.isNotEmpty) {
      _keepAliveLink ??= ref.keepAlive();
    } else {
      _keepAliveLink?.close();
      _keepAliveLink = null;
    }
  }

  void removeTopicById(String topicId) {
    final current = state.valueOrNull;
    final currentData = current?.data;
    if (current == null || currentData == null) return;

    final newData = currentData.where((t) => t.id != topicId).toList();
    final totalSize =
        current.totalSize > 0 ? current.totalSize - 1 : current.totalSize;
    final newState = current.copyWith(
      data: newData,
      totalSize: totalSize,
      hasMore: newData.length < totalSize,
    );
    state = AsyncValue.data(newState);
    _updateKeepAlive(newState);
  }
}
